package db4oToOracle.obj1test;


import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.googlecode.datawander.connectors.Db4oUtil;
import com.googlecode.datawander.connectors.OracleConnector;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MarcinStachniuk
 */
class Animal {

    private String name;
    private List<AppUser> owners;

    public Animal(String name) {
        this.name = name;
    }

    public static void saveAllRecords(Animal [] animals) throws Exception {
        if(animals != null) {
            Connection conn = OracleConnector.getConnection();
            for(Animal o : animals) {
                o.saveRecord(conn);
            }
        }
    }

    private void saveRecord(Connection conn) throws SQLException {
                String sql = "insert into \"Animal\" (\"GENERATED_ID\", \"name\") " +
                "values (?,?)";
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setLong(1, getIdFromDb4o());
        stmt.setString(2, name);

        stmt.executeUpdate();
        System.out.println("Zapisano Animal id: "+getIdFromDb4o() + " name: " +
                name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<AppUser> getOwners() {
        return owners;
    }

    public void setOwners(List<AppUser> owners) {
        this.owners = owners;
    }

    public void addOwner(AppUser user) {
        if(this.owners == null) {
            owners = new ArrayList<AppUser>();
        }
        owners.add(user);
    }

    /**
     * Pobiera id z db4o. Zakładam ze wynik bedzie inny niz zero, w przeciwnym
     * wypadku bedzie to obiekt ktorego nie bylo w db4o
     * @return
     */
    public long getIdFromDb4o() {
        ObjectContainer db = Db4oUtil.getObjectContainer();
        long id = db.ext().getID(this);
        return id;
    }

}
